package com.example.springboot.filter;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;

public class CustomFilter {
/**
 * 用户自定义Filter，通过Filter进行数据过滤，在这里可以通过ioc注入方式或者配置文件的方式针对多种情况添加不通的过滤器
 */
    public void searchByCustomFilter(){
        try {
            Directory directory= FSDirectory.open(new File("E:\\java-source\\lucene\\lucene-index\\2"));
            IndexSearcher search = new IndexSearcher(DirectoryReader.open(directory));
            Query q = new TermQuery(new Term("content","hello"));
            TopDocs tds = search.search(q, new MyIDFilter(new FilterAccessor() {

                @Override
                public String[] needOperateValues() {
                    /**显示ID**/
                    String[] ids = new String[]{"tangmayao"};
                    return ids;

                    /**按照fileName进行展示
                     String[] fileNames = new String[]{"MySameAnalyzer.txt","MySameAnalyzer副本 13.txt"};
                     return fileNames;**/
                }

                @Override
                public String getField() {
                    String field = "name";
                    /** String field = "fileName";**/
                    return field;
                }

                @Override
                public boolean hasSet() {
                    return false;
                }

            }),10);
            for(ScoreDoc sd:tds.scoreDocs) {
                Document d = search.doc(sd.doc);
                System.out.println(sd.doc+":("+sd.score+")" +
                        "["+d.get("id")+"【"+d.get("name")+"】--->"+
                        d.get("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}